﻿namespace Snipps.Infrastructure.Behaviors
{
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Interactivity;

    public class InsertTabSpaceBehavior : Behavior<TextBox>
    {
        private const string _tab = "\t";

        public Key Key { get; set; }

        public ModifierKeys Modifiers { get; set; }

        protected override void OnAttached()
        {
            AssociatedObject.PreviewKeyDown += AssociatedObject_PreviewKeyDown;
        }

        private void AssociatedObject_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyboardDevice.Modifiers == Modifiers && e.Key == Key)
            {
                var caretIndex = AssociatedObject.CaretIndex;
                AssociatedObject.Text = AssociatedObject.Text.Insert(caretIndex, _tab);
                AssociatedObject.CaretIndex = caretIndex + 1;
                e.Handled = true;
            }
        }

        protected override void OnDetaching()
        {
            AssociatedObject.PreviewKeyDown -= AssociatedObject_PreviewKeyDown;
        }
    }
}